package com.css.security.browser.authentication;

import com.css.common.core.utils.R;
import com.css.common.security.constant.SecurityConstants;
import com.css.common.security.enums.LoginResponseType;
import com.css.common.security.properties.SecurityProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * CssAuthenticationFailureHandler
 * 浏览器环境下登录失败适配器
 *
 * @author hanyx
 * @date 2019/04/11
 */
@Slf4j
@Component("cssAuthenticationFailureHandler")
public class CssAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private SecurityProperties securityProperties;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        log.info("登录失败");
        if (LoginResponseType.JSON.equals(securityProperties.getBrowser().getSignInResponseType())) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setContentType(SecurityConstants.APPLICATION_JSON_CONTENT_TYPE);
            response.getWriter().write(objectMapper.writeValueAsString(new R(exception)));
        } else {
            super.onAuthenticationFailure(request, response, exception);
        }
    }
}
